<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title id="titleKey">浩鲸知识库</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="shortcut icon" href="<%=basePath%>modules/micro/imgs/logo.ico">
    <link href="<%=basePath%>frm/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="<%=basePath%>frm/bootstrap-3.3.7/css/bootstrap-treeview.css" rel="stylesheet">

    <script type="text/javascript" charset="utf-8" src="<%=basePath%>frm/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="<%=basePath%>frm/ueditor/ueditor.all.min.js"> </script>
    <script type="text/javascript" charset="utf-8" src="<%=basePath%>frm/ueditor/lang/zh-cn/zh-cn.js"></script>
  </head>
  <body onload="getKnowlibCode();qrySubjectDataById();">
    <div style="position:relative;width:100%;">
      <div id="titleDiv" class="panel-heading" style="background-image: url(<%=basePath%>modules/micro/imgs/bgimg.jpg);color: #ffffff;margin:auto;width:100%">
        <h3 class="panel-title">
          <a href="<%=basePath%>"><h1 id="knowTitle">浩鲸知识库</h1></a>
        </h3>
        <div id="toolbarDiv" style="display: none;position: relative;width: 850px;margin-top: -73px;float: right;"></div>
      </div>
      <div id="myPageDiv">
        <ul class="nav nav-tabs nav-pills">
          <%--<li ><a class="glyphicon glyphicon-hand-right" href="#" onclick="replyFunc()">回复</a></li>--%>
         <!--
          <li ><a href="#">实名回复</a></li>
          -->
          <li><a class="glyphicon glyphicon-menu-hamburger" href="#" onclick="menuOprate()" id="menuLabel">隐藏菜单</a></li>
          <li><a class="glyphicon glyphicon-home" href="<%=basePath%>">首页</a></li>
          <li><a class="glyphicon glyphicon-pencil" href="#" onclick="edit()" id="oprateBtn">编辑</a></li>
          <li ><a class="glyphicon glyphicon-eye-open" href="#" onclick="lookFunc()">全屏预览</a></li>
            <li ><a class="glyphicon glyphicon-eye-open" href="#" onclick="exportWord()">导出word</a></li>
          <%--<li><a class="glyphicon glyphicon-arrow-up" href="<%=basePath%>modules/micro/html/micro.jsp">返回上一页</a></li>--%>
        </ul>
      </div>
    </div>
    <div style="overflow: hidden" id="parentDiv">
      <div id="treeview" style="margin:auto;width:250px;float:left; overflow-x:hidden;white-space:nowrap"></div>
      <form id="subjectForm" action="<%=basePath%>subject/insertReplySubject.do" method="post">
      <div id="rightDiv" style="display: none;">
        <div class="row" style="color:blue;font-family: bold;margin-top:2px;overflow:auto;font-size: 25px;text-align: center;">
          <div style="border:1px solid #f5f5f5;">
            <span id="subjectTitleSpan" style="font-weight: bold"></span>
            <input type="text" id="subjectTitle" name="subjectTitle" style="margin-top: 7px;margin-bottom: 2px;width:100%;color: #080808;display:none;text-align: center">
          </div>
        </div>

        <div style="margin:auto;width:100%;height:100%;margin-top:2px;">
          <div id="subjectDetailDiv" style="font-family: bold;position:relative; height:100%; overflow:auto;text-align: left;">
            <div id="subjectContent" type="text/plain" style="width:100%;position:relative; height:100%; overflow:hidden;"></div>
          </div>
        </div>
      </div>
      </form>
    </div>
    <div id="myIframe" style="display:none; width:100%;font-family: bold;overflow: visible;font-size: 16px;text-align: left;">
      <ul class="nav nav-tabs nav-pills">
        <li ><a href="#" onclick="window.history.back(-1)">返回</a></li>
      </ul>
      <iframe id="iframepage" name="iframepage" frameBorder=0 overflow:scroll width="100%"></iframe>
    </div>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/jquery.min.js"></script>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <script src="<%=basePath%>frm/bootstrap-3.3.7/js/bootstrap-treeview.js"></script>
    <script src="<%=basePath%>frm/layer/layer.js"></script>
    <%
      String subjectId = (String)request.getParameter("subjectId");//直接传递
      String url = (String)request.getParameter("url");//直接传递
    %>

    <script type="application/javascript">
      var initSubjectId = '<%=subjectId%>';
      var selectNode = {};
      var selectedItem = {};
      var exportObj = {};
      var initSubjectTitle;
      $(window).resize(function () {          //当浏览器大小变化时
          var curScreemHeight = $(document).height() - 180;
          $("#subjectDetailDiv").height(curScreemHeight);
          $("#parentDiv").height(curScreemHeight+42);
          $("#treeview").height($(document).height()-140);
      });

      var curScreemHeight = $(document).height() - 180;
      $("#subjectDetailDiv").height(curScreemHeight);
      $("#parentDiv").height(curScreemHeight+42);
      $("#treeview").height($(document).height()-140);

//      $("#subjectContent").on('keydown', function(e){
//          var keycode = e.keyCode || e.which;
//          if((e.ctrlKey && keycode == 35)||
//              e.ctrlKey && keycode.keyCode == 36){
//              alert("ctrl+end不能使用");
//              event.preventDefault();
//          }
//      });
      var ue;

      // 预览弹出窗口 esc键退出
      $('body',document).on('keyup', function (e) {
          if (e.which === 27) {
              // console.log("按下esc");
              layer.closeAll();
          }
      });

      //加载层-默认风格
      layer.load();
      /**
       * 查询初始化主题数据
       */
      function qrySubjectDataById() {
        ue = UE.getEditor('subjectContent',{
          autoHeightEnabled: true,
          autoFloatEnabled: false,
          enableAutoSave: false
        });

        $("#toolbarDiv").hide();
        $("#toolbarDiv").html($("#edui1_toolbarbox")[0]);
        // $("#edui1_toolbarbox").css("display", "none");

        if(initSubjectId) {
          $("#titleDiv").show();
          $("#myPageDiv").show();
          $("#myIframe").hide();
          $.post("<%=basePath%>subject/qrySubjectById.do", {subjectId:initSubjectId}, function result(data) {
            var subjectData = JSON.parse(data);
              if (subjectData) {
                  selectedItem = subjectData;
                  queryInitData('all');
                  initSubjectTitle = subjectData.subjectTitle;
                  var modifyUser = subjectData["modifyUserName"] || '无数据';
                  $("#subjectTitleSpan").html(subjectData.subjectTitle);
                  $("#subjectTitleSpan").attr("title", "最后更新："+modifyUser +  "，更新时间：" + subjectData.modifyDate);
                  $("#subjectTitle").val(subjectData.subjectTitle);
                  $("#subjectTitle").attr("title", "更新时间：" + subjectData.modifyDate);
                  $("#titleKey").html(subjectData.subjectTitle);
                  ue.ready(function() {
                      subjectData.subjectContent = subjectData.subjectContent == null?'无内容' : subjectData.subjectContent;
                      //异步回调
                      ue.setContent(subjectData.subjectContent);
                      ue.setDisabled();
                      exportObj = subjectData;
                      $("#rightDiv").show();

                      // 重置滚轮
                      $("#subjectDetailDiv")[0].scrollTop = 0;

                      layer.closeAll('loading');
                  });
              } else {
                  layer.confirm('手动修改浏览器地址就算了，你还改错了，玩崩了吧，是否回到首页?', {icon: 3, title:'提示'}, function(){
                      window.location.href="<%=basePath%>";
                  }, function(){
                      $("#rightDiv").hide();
                  });
              }
          });
        } else {
          $("#myIframe").show();
          $("#titleDiv").hide();
          $("#myPageDiv").hide();

          iFrameHeight()
        }
      }

      function iFrameHeight() {
        var ifm= document.getElementById("iframepage");
        ifm.src = "<%=url%>";
        ifm.height = $(document).height() - 50;
        $("#subjectContent").height($(document).height()-150);
      }

      /**
       * 匿名回复当前条目
       */
      function replyFunc() {
        if(initSubjectId) {
          window.location.href="anonymouReplySubject.jsp?subjectId=" + initSubjectId;
        }
      }

      /**
       * 匿名编辑当前条目
       */
      function edit() {
          if (isLogin()) {
              var oprateFlag = $("#oprateBtn").html();
              if (oprateFlag === "编辑") {
                  $.post("<%=basePath%>subject/getCache.do", {flag: "N", subjectId:initSubjectId}, function result(data) {
                      // 有缓存
                      if (data != "false") {
                          var allData = JSON.parse(data);
                          layer.confirm("【"+allData.userName + '】正在编辑文档中，是否强制开启编辑?', {icon: 3, title:'提示'}, function(index){
                              layer.close(index);
                              menuOprate();
                              // 设置编辑器可编辑
                              ue.setEnabled();
                              $("#toolbarDiv").show();
                              $("#oprateBtn").html("保存");
                              $("#oprateBtn").attr("class", "glyphicon glyphicon-ok");
                              setCache("N");
                          });
                      } else {
                          menuOprate();
                          // 设置编辑器可编辑
                          ue.setEnabled();
                          $("#toolbarDiv").show();
                          $("#oprateBtn").html("保存");
                          $("#oprateBtn").attr("class", "glyphicon glyphicon-ok");
                          setCache("N");
                      }
                  });
              } else {
                  saveSubject()
              }
          }
      }

      /**
       * 确认编辑 设置缓存
       * */
      function setCache(flag) {
          $.post("<%=basePath%>subject/setCache.do", {flag: flag, subjectId:initSubjectId, userName:window.userName}, function result(data) {
              // 有缓存
              if (data === "true") {
                  console.log("缓存已设置，有效期三分钟!");
              } else {
                  console.log("缓存设置失败!");
              }
          });
      }

      /**
       * 保存匿名回复的主题
       */
      function saveSubject() {
          if (isLogin()) {
              var subjectTitle = $("#subjectTitle").val();
              var subjectContent = ue.getContent();
              if(subjectContent) {
                  layer.load();
                  $.post("<%=basePath%>subject/insertReplySubject.do", {flag: "edit", subjectId:initSubjectId, subjectTitle:subjectTitle, subjectContent:subjectContent,modifyUserName:window.userName,subjectCatName:selectedItem.subjectCatName}, function result(data) {
                      layer.closeAll('loading');
                      menuOprate();
                      layer.msg('修改成功!', {icon: 1});
                      $("#toolbarDiv").hide();
                      querySubjectDetailById();
                      // 只有标题变更了才需要重新查菜单
                      if (initSubjectTitle != subjectTitle) {
                          queryInitData('all');
                      }
                  });
              } else {
                  layer.msg('请填写文档内容!', {icon: 5});
              }
          }
      }

      /**
       * 切换非编辑状态
       */
      function initStatus() {
          // 重置滚轮
          $("#subjectDetailDiv")[0].scrollTop = 0;
          // 隐藏工具栏
          // $("#edui1_toolbarbox").css("display", "none");
          // 设置编辑器不可编辑
          ue.setDisabled();
          // 设置 span 标题栏显示
          $("#subjectTitleSpan").css("display", "block");
          // 设置修改标题栏隐藏
          $("#subjectTitle").css("display", "none");

          $("#oprateBtn").html("编辑");
          $("#oprateBtn").attr("class", "glyphicon glyphicon-pencil");

          // 显示菜单
          $("#menuLabel").html("隐藏菜单");
          $("#treeview").css("display", "block");
      }

      /**
       * 查询初始化主题数据
       */
      function queryInitData(condition) {
          //加载层-默认风格
          layer.load();
          $.post("<%=basePath%>subject/qryInitData.do", {condition: condition,subjectCatName:selectedItem.subjectCatName||"changsha"}, function result(data) {
              var allData = JSON.parse(data);
              var rootData = getTree(allData, "subjectId", "pSubjectId", "-1", condition) || [];
              //  // 遍历根节点 递归组装Tree结构树
              if(rootData) {

                  var options = {
                      color: "#428bca",
                      expandIcon: 'glyphicon glyphicon-chevron-right',
                      collapseIcon: 'glyphicon glyphicon-chevron-down',
                      nodeIcon: 'glyphicon glyphicon-bookmark',
                      //onhoverColor: "#86BF4B",
                      borderColor: "red",
                      showBorder: false,
                      showTags: true,
                      highlightSelected: true,
                      selectedColor: "yellow",
                      selectedBackColor: "darkorange",
                      enableLinks: true,
//                      onNodeChecked: nodeChecked,
                      data: rootData
                  };

                  $('#treeview').treeview(options);
                  layer.closeAll('loading');
                  $('#treeview').on('nodeSelected', function(event, data) {
                      selectedItem = data;
                      $("#toolbarDiv").hide();
                      // 重置浏览器URL，以便刷新
                      history.pushState("", "Title", "<%=basePath%>modules/micro/html/subjectDetail.jsp?subjectId="+selectedItem.subjectId);
                      var oprateFlag = $("#oprateBtn").html();
                      if (oprateFlag === "保存") {
                          layer.confirm('您正在编辑文档，是否强制退出?', {icon: 3, title:'提示'}, function(index){
                              layer.close(index);
                              // 清除编辑缓存
                              setCache("Y");
                              // 点击菜单与详情ID不同的时候再查
                              if(initSubjectId != selectedItem.subjectId) {
                                  layer.load();
                                  $("#rightDiv").hide();
                                  initSubjectId = selectedItem.subjectId;
                                  querySubjectDetailById();
                              }
                          }, function(){
                              $("#toolbarDiv").show();
                              $($("a:contains('"+selectedItem.subjectTitle+"')")[0]).css("color", "#428bca");
                              $($("a:contains('"+selectedItem.subjectTitle+"')")[0]).parent().css("background-color", "#FFFFFF");

                              // 设置正在编辑标题对应的菜单
                              $($("a:contains('"+$("#subjectTitle").val()+"')")[0]).css("color", "#FFFF00");
                              $($("a:contains('"+$("#subjectTitle").val()+"')")[0]).parent().css("background-color", "#FF8C00");
                          });
                      } else {
                          // 点击菜单与详情ID不同的时候再查
                          if(initSubjectId != selectedItem.subjectId) {
                              layer.load();
                              $("#rightDiv").hide();
                              initSubjectId = selectedItem.subjectId;
                              querySubjectDetailById();
                          }
                      }
                  });

                  //节点取消选中时触发
                  $('#treeview').on('nodeUnselected', function(event, data) {
                      selectedItem = {};
                  });
                  // 收缩所有节点
                  $('#treeview').treeview('expandAll', { silent: false });

                  $($("a:contains('"+selectNode.subjectTitle+"')")[0]).css("color", "#FFFF00");
                  $($("a:contains('"+selectNode.subjectTitle+"')")[0]).parent().css("background-color", "#FF8C00");
              }
          });
      }

      /**
       * 重新查询主题详情
       * */
      function querySubjectDetailById() {
          initStatus();
          $.post("<%=basePath%>subject/qrySubjectById.do", {subjectId:selectedItem.subjectId}, function result(data) {
              var subjectData = JSON.parse(data);
              if (subjectData) {
                  $("#rightDiv").show();
                  initSubjectTitle = subjectData.subjectTitle;
                  var modifyUser = subjectData["modifyUserName"] || '无数据';
                  $("#subjectTitleSpan").html(subjectData.subjectTitle);
                  $("#subjectTitleSpan").attr("title", "最后更新："+modifyUser +  "，更新时间：" + subjectData.modifyDate);
                  $("#subjectTitle").val(subjectData.subjectTitle);
                  $("#titleKey").html(subjectData.subjectTitle);
                  ue.ready(function() {
                      subjectData.subjectContent = subjectData.subjectContent == null?'无内容' : subjectData.subjectContent;
                      //异步回调
                      ue.setContent(subjectData.subjectContent);

                      exportObj = subjectData;
                      // 重置滚轮
                      $("#subjectDetailDiv")[0].scrollTop = 0;
                      layer.closeAll('loading');
                  });
              } else {
                  layer.confirm('手动修改浏览器地址就算了，你还改错了，玩崩了吧，是否回到首页?', {icon: 3, title:'提示'}, function(){
                      window.location.href="<%=basePath%>";
                  }, function(){
                      $("#rightDiv").hide();
                  });
              }
          });
      }

      function getTree(srcData, selfField, parentField, topFlag, condition) {
          var tree = new Array();
          if (srcData) {
              var dict = new Array();
              // add  roodnode
              var n = srcData.length;
              for (var i = 0; i < n; i++) {
                  var item = srcData[i];
                  item.text = item["subjectTitle"];
                  <%--item.href = "<%=basePath%>modules/micro/html/"+item["subjectLink"];--%>
                  dict[item[selfField]] = item;
                  if (item[parentField] == topFlag || item[parentField] == "" || condition != 'all') {
                      tree[tree.length] = item; // 添加根节点
                  }
                  // 设置初始化选中的节点
                  if (initSubjectId == item.subjectId) {
                      selectNode = item;
                  }
              }
              // 由下至上，构造树
              for (var j = 0; j < n; j++) {
                  //var tags = 0;
                  var child = srcData[j];
                  if (child[parentField] == topFlag || child[parentField] == "") {
                      continue;
                  }
                  // 设置初始化选中的节点
                  if (initSubjectId == child.subjectId) {
                      selectNode = child;
                  }
                  var parent = dict[child[parentField]];
                  //parent.tags = [tags];
                  if (parent) {
                      //child.parent = parent;
                      if (!parent.nodes) {
                          parent.nodes = new Array();
                      }
                      //tags += parent.nodes.length;
                      parent.nodes[parent.nodes.length] = child;
                  }
              }
              return tree;
          }
      }

      /**
       * 显示菜单
       */
      function menuOprate() {
          var displayVue = $("#treeview").css("display");
          if (displayVue == 'block') {
              $("#menuLabel").html("显示菜单");
              $("#treeview").css("display", "none");
          } else {
              $("#menuLabel").html("隐藏菜单");
              $("#treeview").css("display", "block");
          }
      }

      /**
       * 预览
       */
      function lookFunc() {
          if(initSubjectId) {
              layer.open({
                  type: 2,
                  title: [initSubjectTitle,'font-size:18px;color:blue;'],
                  //title:['快速浏览'],
                  shadeClose: true,//点击遮罩关闭层
                  shade: 0.8,
                  area: ['100%', '100%'],
                  move: false,
                  content: "<%=basePath%>modules/micro/html/subjectLookDetail.jsp?subjectId=" + initSubjectId
                  ,scrollbar: false
              });

          } else {
              //alert("请选中您要回复的主题!");
              //layer.alert("请选中您要回复的主题!");
              layer.msg('请选中您要快速浏览的主题!', {icon: 5});
          }
      }

      /**
       *
       * 导出word
       */
      function exportWord() {
          if (isLogin()) {
              if (exportObj && exportObj.subjectTitle && exportObj.subjectId) {
                  var exportUrl = "<%=basePath%>modules/micro/html/exportWord.jsp?subjectId="+exportObj.subjectId;
                  window.location.href = exportUrl;
              } else {
                  layer.msg('没有要导出的数据，请重新选择菜单!', {icon: 5});
              }
          }
      }

      /**
       * 从cookie中获取用户信息
       * */
      function isLogin() {
          // 如果未登陆给出提示
          var hasCook = false;
          var cookieVue = document.cookie;
          var cookieArr = decodeURI(cookieVue).split(";");
          if (cookieArr) {
              for (var i=0;i<cookieArr.length;i++) {
                  if (cookieArr[i].indexOf("username") != -1) {
                      var uname = cookieArr[i].split("=");
                      hasCook = true;
                      window.userName = uname[1];
                  }
                  if (cookieArr[i].indexOf("knowlibcode") != -1) {
                      var knowlibcode = cookieArr[i].split("=");
                      window.knowlibcode = knowlibcode[1] || "changsha";
                  }
              }
              if (!hasCook) {
                  layer.confirm('未登陆，不可编辑，是否跳转登陆页面?', {icon: 3, title:'提示'}, function(){
                      var sourceUrl = window.location.href;
                      window.location.href="<%=basePath%>modules/micro/login/login.jsp?sourceUrl=" + sourceUrl;
                  });
              }
          }
          return hasCook;
      }

      /**
       * 从缓存中获取知识库
       * */
      function getKnowlibCode() {
          var cookieVue = document.cookie;
          var cookieArr = decodeURI(cookieVue).split(";");
          if (cookieArr) {
              for (var i=0;i<cookieArr.length;i++) {
                  if (cookieArr[i].indexOf("username") != -1) {
                      var uname = cookieArr[i].split("=");
                      window.userName = uname[1];
                  }
                  if (cookieArr[i].indexOf("knowlibcode") != -1) {
                      var knowlibcode = cookieArr[i].split("=");
                      window.knowlibcode = knowlibcode[1] || "changsha";
                  }
              }
          }
      }
    </script>
  </body>
